package com.xunsiya.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.xunsiya.common.config.RequestUtils;
import com.xunsiya.common.config.util.ConstantInfo;
import com.xunsiya.service.system.UserService;
import com.xunsiya.system.vo.User;
import com.xunsiya.tools.common.msg.Msg;
import com.xunsiya.tools.common.string.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 用户控制层
 *
 * @author linqy
 * @version 1.0
 *          <p/>
 *          <br/>
 *          <br/>修订人    修订时间      描述信息
 *          <br/>-----------------------------------------------------
 *          <br/>linqy    2017/11/11    初始创建
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户列表 分页查询
     *
     * @param user
     * @return
     */
    @PostMapping
    public Msg queryUserList(@RequestBody User user,
                             @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if (user != null && !StringUtil.isEmpty(user.getUserName())) {
            user.setUserName("%" + user.getUserName() + "%");
        }
        return userService.queryFilterUserForPage(user, pageIndex, pageSize);
    }

    @GetMapping("/{id}")
    public User queryUserInfo(@PathVariable int id) {
        User user = new User();
        user.setId(id);
        List<User> list = userService.queryUser(user);
        user = list.get(0);
        return user;
    }

    @PostMapping("/insert")
    public Msg addUser(@RequestBody User user) throws Exception {
        user.setCreateTime(new Date());
        user.setStatus(0);
        return userService.insertUser(user);
    }

    @PostMapping("/update")
    public Msg modifyUser(@RequestBody User user) {
        return userService.modifyUser(user);
    }

    @PostMapping("/delete")
    public Msg deleteUser(@RequestBody JSONObject requestBody) {
        int id = requestBody.getInteger("id");
        User user = RequestUtils.getSessionAttribte(User.SYS_LOGIN_INFO);
        if (id == user.getId()) {
            return new Msg(false, "不能删除自己!");
        }
        return userService.deleteUser(id);
    }

    /**
     * 用户修改个人信息
     *
     * @param user
     * @return
     */
    @PostMapping("/modifyUserInfo")
    public Msg modifyUserInfo(@RequestBody User user) {
        Msg msg = new Msg(false);
        if (StringUtil.isEmpty(user.getRealName())) {
            msg.setMsg(ConstantInfo.HttpCode.HTTP_400.getDesc() + ",姓名不能为空,请重新输入！");
            return msg;
        }
        return userService.modifyUserInfo(user);
    }

}
